<?php
/**
 * Database abstraction class.
 * Works with SQLite only at the moment.
 */
class AtbudgetDB extends SQLite3 {
	function __construct($fname)
	{
		$this->open($fname);
		$this->busyTimeout(2000);
	}
}

	$db = new AtbudgetDB('../atbudget.sqlite');
	try {
		switch ($_SERVER['REQUEST_METHOD']) {
			case 'GET': //list payees
				header('Content-type: application/json');
				$res = $db->query('SELECT * FROM payee ORDER BY name');
				$payees = array();
				$i = 0;
				if ($res) {
					while ($row = $res->fetchArray(SQLITE3_ASSOC)) {
						$payees[$i] = $row;
						$i++;
					}
				}
				echo json_encode(array('success' => 'true', 'payees' => $payees));
				break;
			case 'POST': //new payee
				header('Content-type: application/json');
				$payee = json_decode($HTTP_RAW_POST_DATA);
				if ($payee->name == '') {
					echo json_encode(array('success' => 'false', 'msg' => 'Failed to create record. Invalid data.','payees' => array()));
				} else {
					if ($db->exec('INSERT INTO payee (name, description) VALUES ("'.$payee->name.'","'.$payee->description.'")')) {
						$payee->id = $db->lastInsertRowID();
						echo json_encode(array('success' => 'true','payees' => array($payee)));
					} else {
						echo json_encode(array('success' => 'false', 'msg' => 'Failed to create record. Database failure.','payees' => array()));
					}
				}
				break;
			case 'PUT': //save payee
				header('Content-type: application/json');
				echo json_encode(array('success' => 'false', 'msg' => 'Not implemented yet.', 'payees' => array()));
				break;
			case 'DELETE': //delete payee
				header('Content-type: application/json');
				echo json_encode(array('success' => 'false', 'msg' => 'Not implemented yet.', 'payees' => array()));
				break;
			default:
				header('Content-type: application/json');
				echo json_encode(array('success' => 'false', 'msg' => 'Server cannot handle your request.','payees' => array()));
		}//switch
	} catch (Exception $e) {
	}
	$db->close();
